package com.team.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.team.dao.ProjDao;
import com.team.dao.UserDao;
import com.team.dao.UserProjectDao;
import com.team.entity.Project;
import com.team.entity.User;
import com.team.entity.UserProject;
import com.team.util.Const;
import com.team.util.ObjectUtil;
import com.team.util.StringUtil;

public class NewProjectServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("_m");
		if("save".equals(method)){
			save(request,response);
		}else if("select".equals(method)){
			selectForAll(request,response);
		}else if("edit".equals(method)){
			edit(request,response);
		}else if("update".equals(method)){
			updataProject(request,response);
		}else if("del".equals(method)){
			del(request,response);
		}else {
			response.sendError(404,"请求一个不存在的路径");
			return ;
		}
	}
	private void del(HttpServletRequest request,
			HttpServletResponse response)  throws IOException {
		String projId = request.getParameter("projId");
		int id = Integer.parseInt(projId);
		System.out.println("del中的id"+id);
		
		ProjDao dao = new ProjDao();
		dao.del(id);
		response.sendRedirect("listProj.jsp");
	}
	/**
	 * 修改项目信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void updataProject(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String projId = request.getParameter("projId");
		System.out.println("projectid update"+projId);
		
		String projname = request.getParameter("projname");
		String leader = request.getParameter("leader");
		String member = request.getParameter("member");//string
		String time = request.getParameter("time");
		String text = request.getParameter("text");
		String endtime = request.getParameter("endtime");
		
		if(StringUtil.isEmpty(projId)||StringUtil.isEmpty(projname)
				||StringUtil.isEmpty(leader)||StringUtil.isEmpty(member)
				||StringUtil.isEmpty(text)||StringUtil.isEmpty(time)
				||StringUtil.isEmpty(endtime)){
			
			response.sendRedirect("projReset.jsp?code=1001");
			return ;
			
		}
			//首先更新project表
			//在更新关系表，其中projectid，t_user表 不动
			Project proj = new Project();
			int projectId = Integer.parseInt(projId);
			
			proj.setId(projectId);
			proj.setCreateTime(time);
			proj.setContent(text);
			proj.setEndTime(endtime);
			proj.setProjName(projname);
			
			ProjDao pd  = new ProjDao();
			int num = pd.updateProj(proj);
			if(num > 0){
				System.out.println("t_project修改成功");
				UserDao ud = new UserDao();
				User user = ud.selectByName(leader);//leader
				
				String[] values = member.split(";");
				for(String str:values){
					System.out.println("update str→"+str);
					
				}
				List<User> members = new ArrayList<User>();//member
				for(String str :values){
					User temp = ud.selectByName(str);
					if(temp == null){
						response.sendRedirect("projReset.jsp?code=1003");
						return ;
					}else {
						System.out.println("temp username\t"+temp.getUsername());
						members.add(temp);
					}
				}
				
				if(ObjectUtil.isEmpty(user)||ObjectUtil.isEmpty(members)){
					response.sendRedirect("projReset.jsp?code=1003");
					return ;
				}
				
				System.out.println("update leader and members");
				
				
				
				
				
				
				
			}else {
				
				System.out.println("t_project修改fail");
				
			}
			
			
}
			
		
		
	
/**
 * 查找项目信息
 * @param request
 * @param response
 * @throws IOException
 */
	private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String projId = request.getParameter("projId");
		int id = Integer.parseInt(projId);
		
		ProjDao dao = new ProjDao();
		Project proj = dao.selectById(Integer.parseInt(projId));
		HttpSession session = request.getSession();
		if(proj != null){
			 session.setAttribute(Const.SESSION_RESET_PROJ, proj);
			System.out.println(projId+"→项目查找成功");
			
			UserDao ud = new UserDao();
			List<User> memberList = new	ArrayList<User>();
			
			UserProjectDao upd = new UserProjectDao();
			List<UserProject> list = upd.selectByProjId(id);
			
			if(list != null){
				System.out.println(projId+"→t_user_project关系表查找成功");
				for(UserProject up : list){
					
					System.out.println(up.getRole());
					if("admin".equals(up.getRole())){
						//admin 
						//System.out.println("admin");
						User user = ud.selectById(up.getUserId());
						if(user == null){
							System.out.println("user find error");
							
						}else {
							System.out.println("user find succ");
							session.setAttribute(Const.SESSION_RESET_USER, user);
						}
					}else if("member".equals(up.getRole())){
						//member
						//System.out.println("member");
						User temp = ud.selectById(up.getUserId());
						if(temp != null){
							memberList.add(temp);
						}else {
							System.out.println("member此用户不存在！！");
						}
					}
				}
				session.setAttribute(Const.SESSION_RESET_MEMBERLIST, memberList);
				
			}else {
				System.out.println(projId+"→t_user_project关系表查找失败");
			}
		}else {
			System.out.println(projId+"→项目查找失败");
		}
	response.sendRedirect("projReset.jsp");
	return ;
	}

	private void selectForAll(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ProjDao pd = new ProjDao();
		UserDao ud = new UserDao();
		UserProjectDao upd = new UserProjectDao();
		ServletContext application = getServletContext();
		List<Project> list = pd.selectAllProject();
		//find admin→name
		Map<Project,User> map = new HashMap<Project,User>();
		for(Project project :list){
			//根据项目id，找到项目负责人姓名
			List<UserProject> userProjList = upd.selectByProjId(project.getId());
			for(UserProject up: userProjList){
				if("admin".equals(up.getRole())){
					User user = ud.selectById(up.getUserId());
					map.put(project,user);
				}
				
			}
			
		}
		
		application.setAttribute(Const.APPLICATION_ADMIN, map);
		application.setAttribute(Const.APPLICATION_PROJS, list);
		response.sendRedirect("listProj.jsp");
		return ;		
	}
	private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String projname = request.getParameter("projname");
		String leader = request.getParameter("leader");
		String member = request.getParameter("member");//string
		String time = request.getParameter("time");
		String text = request.getParameter("text");
		String endtime = request.getParameter("endtime");
		UserDao ud = new UserDao();
		UserProjectDao upd = new UserProjectDao();
		
		if(StringUtil.isEmpty(projname)||StringUtil.isEmpty(leader)
				||StringUtil.isEmpty(member)||StringUtil.isEmpty(time)
				||StringUtil.isEmpty(endtime)){
			response.sendRedirect("newProj.jsp?code=1001");
			return;
		}
		
		Project proj = new Project();
		proj.setProjName(projname);
		proj.setCreateTime(time);
		proj.setContent(text);
		proj.setEndTime(endtime);
	
		ProjDao pd = new ProjDao();
		int num = pd .saveProj(proj);
		if(num >0){
			System.out.println("succ");
			Project project = pd.selectProjId(proj);
			if(project != null){
				System.out.println(project.getId());
				User user  = ud.selectByName(leader);
				if(user != null){
					System.out.println("user id find succ");
					System.out.println(user.getId());
					int num1= upd.saveUserAndProject(user, project, "admin");
					if(num1 >0 ){
						System.out.println("leader link save succ");
						List<User> userList = new ArrayList<User>();
						String[] values = member.split(";");
						for(String str:values){
							System.out.println(str);
							User temp = ud.selectByName(str);
							if(temp != null){
								userList.add(temp);
							}else {
								response.sendRedirect("newProj.jsp?code=1003");
								return ;
							}
						}
						for(User tempUser :userList){
							int num2 = upd.saveUserAndProject(tempUser, project, "member");
							if(num2 < 0){
								response.sendRedirect("newProj.jsp?code=1004");
								return ;
							}
						}
						response.sendRedirect("newProj.jspx?_m=select");
						return ;
					}else {
						System.out.println("leader save error");
					}
				}else {
					System.out.println("user find error");
				}
			}
		}else {
			System.out.println("error");
			response.sendRedirect("newProj.jsp?code=1002");
			return ;		
			
		}
				
	}
}
